package de.bazinga.rotw.network.message.physics;

import com.captiveimagination.jgn.message.Message;
import com.captiveimagination.jgn.message.type.CertifiedMessage;
import com.captiveimagination.jgn.message.type.PlayerMessage;
import com.captiveimagination.jgn.message.type.TimestampedMessage;
import com.jme.math.Vector3f;
import com.jme.scene.Spatial;
import com.jmex.jbullet.nodes.PhysicsNode;

import de.bazinga.rotw.collision.CollidableObjects;
import de.bazinga.rotw.game.RotwGameState;
import de.bazinga.rotw.network.Server;
import de.bazinga.rotw.network.message.GameMessage;
import de.bazinga.rotw.vehicle.Car;

public class AppliedForceMessage extends Message implements CertifiedMessage, PlayerMessage, TimestampedMessage, GameMessage {
	private Vector3f force = null;
	private int physicsIndex = 0;
	
	public static final int PHYSICS = 0;
	public static final int CAR = 1;
	
	private int type = AppliedForceMessage.PHYSICS;
	
	
	
	public void handleMessage(RotwGameState game, Message msg, boolean server) {
		if(!(msg instanceof AppliedForceMessage)) return ;
		
		if(type == PHYSICS) {
			if(CollidableObjects.getInstance().getObjects("physics").size()  > getPhysicsIndex() && getPhysicsIndex() >= 0) {
				// apply force
				Spatial obj = CollidableObjects.getInstance().getObjects("physics").get(getPhysicsIndex());
				if(obj instanceof PhysicsNode) {
					((PhysicsNode)obj).applyImpulse(getForce(), Vector3f.ZERO);
				}
			}
		}else if(type == CAR) {
			if(CollidableObjects.getInstance().getObjects("vehicle").size()  > getPhysicsIndex() && getPhysicsIndex() >= 0) {
				// apply force
				Spatial obj = CollidableObjects.getInstance().getObjects("vehicle").get(getPhysicsIndex());
				if(obj instanceof Car) {
					((Car)obj).getPhysicsCar()
						.applyImpulse(force, Vector3f.ZERO);
				}
			}
			
		}
		
		if(server) {	
			((Server)game.getSyncManager()).getServer().sendToAllExcept(this, getPlayerId());
		}
	}



	public void setPhysicsIndex(int physicsIndex) {
		this.physicsIndex = physicsIndex;
	}



	public int getPhysicsIndex() {
		return physicsIndex;
	}



	public void setForce(Vector3f force) {
		this.force = force;
	}



	public Vector3f getForce() {
		return force;
	}



	public int getType() {
		return type;
	}



	public void setType(int type) {
		this.type = type;
	}
}